# coding=utf-8
import random

import time

from core.m_logging import logger
from core.request import Request


class RetryableRequest(object):
    def __init__(self, rqst, retry=3, min_wandering=1, max_wandering=5, retry_check=None):
        self.rqst = rqst
        self.retry = retry
        self.min_wandering = min_wandering
        self.max_wandering = max_wandering
        self.retry_check = retry_check

    def request(self):
        for i in range(self.retry):
            if i > 0:
                logger.info("retry %s to request..." % i)
                wandering = random.random() * (self.max_wandering - self.min_wandering) + self.min_wandering  # wandering 5 to 50 seconds
                logger.info("wandering %s seconds..." % wandering)
                time.sleep(wandering)

            response = self.rqst.request()
            if self.retry_check:  # customized retry check logic
                if not self.status_code_retry_check(response) and not self.retry_check(response):
                    return response
            else:
                if not self.status_code_retry_check(response):
                    return response

            if i >= self.retry - 1:
                logger.warn("retryableRequest failed, retry %s times..." % self.retry)
                return response

    def middleware(self, middleware):
        self.rqst.middleware_list.append(middleware)
        return self

    def status_code_retry_check(self, response):
        if response.status_code == 200:
            return False
        else:
            return True

